import { ComponentWithStore } from 'mobx-miniprogram-bindings'
import { userStore } from '@/store/userStore'
import { swipeCellBehavior } from '@/behaviors/swipeCell'
import { reqCartList, reqGoodChecked, reqIsAllChecked, reqAddToCart, reqDelGoods } from '@/api/cart'
// 导入防抖函数
import { debounce } from 'miniprogram-licia'

const computedBehavior = require('miniprogram-computed').behavior

ComponentWithStore({
  storeBindings: {
    store: userStore,
    fields: ['token']
  },
  behaviors: [swipeCellBehavior, computedBehavior],

  data: {
    cartList: [],
    emptyDes: '购物车空空如也，快去逛逛吧',
    showEmptyState: false
  },

  methods: {
    // 获取购物车列表
    async getCartList() {
      // 先判断是否已登录
      if (!this.data.token) {
        this.setData({
          emptyDes: '暂无权限查看购物车，请先登录',
          cartList: []
        })
        return
      }
      // 再发起请求获取购物车列表
      const { code, data } = await reqCartList()
      if (code === 200) {
        if (data.length === 0) {
          this.setData({
            showEmptyState: true,
            cartList: []
          })
          return
        }
        this.setData({
          cartList: data,
          showEmptyState: false
        })
      }
    },
    // 更新选中状态
    async onChangeChecked(e) {
      const { id, index } = e.currentTarget.dataset
      const isChecked = e.detail ? 1 : 0
      const res = await reqGoodChecked(id, isChecked)
      if (res.code === 200) {
        // 更新视图勾选状态
        this.setData({
          [`cartList[${index}].isChecked`]: isChecked
        })
      }
    },

    // 全选
    async onSelectedAll(e) {
      const isAllChecked = e.detail ? 1 : 0
      const res = await reqIsAllChecked(isAllChecked)
      if (res.code === 200) {
        // 不推荐在forEach函数里面setData，耗性能
        // 先拷贝(这里用到深拷贝，因为数组中是一个个对象)，再统一赋值
        const newCartList = JSON.parse(JSON.stringify(this.data.cartList))
        newCartList.forEach((item) => {
          item.isChecked = isAllChecked
        })
        this.setData({
          cartList: newCartList
        })
      }
    },
    // 更新数量
    onChangeCount: debounce(async function (e) {
      const newCount = e.detail
      const { goodsid: goodsId, index, oldcount } = e.target.dataset
      // 将差值传给服务器
      const difCount = newCount - oldcount
      // 数量有差值才发请求
      if (difCount == 0) return
      const res = await reqAddToCart({ goodsId, count: difCount })
      if (res.code === 200) {
        // 更新视图
        this.setData({
          [`cartList[${index}].count`]: newCount,
          [`cartList[${index}].isChecked`]: 1
        })
      }
    }, 400),

    async delGoodsBtn(e) {
      const { id } = e.currentTarget.dataset
      // 删除确认
      const delConfirm = await wx.modal({ content: '确定删除该商品吗？' })
      if (delConfirm) {
        const res = await reqDelGoods(id)
        if (res.code == 200) {
          this.getCartList()
        } else {
          wx.toast({ title: '删除失败，请重试' })
        }
      }
    },

    // 去结算
    onSubmit() {
      // 未勾选先提示
      if (!this.data.totalPrice) {
        wx.toast({ title: '请勾选您需要结算的宝贝' })
        return
      }
      wx.navigateTo({
        url: '/modules/orderModule/pages/order/order-detail/order-detail'
      })
    },

    goLook() {
      wx.switchTab({
        url: '/pages/index/index'
      })
    },

    goLogin() {
      wx.navigateTo({
        url: '/pages/login/login'
      })
    },

    goGoodsDetail(e) {
      const goodsId = e.currentTarget.dataset.id
      wx.navigateTo({
        url: `/modules/goodsModule/pages/goods-detail/goods-detail?goodsId=${goodsId}`
      })
    },
    // 空函数，用于阻止事件冒泡
    noop() {},

    // 生命周期函数
    onShow() {
      this.getCartList()
    },

    onHide() {
      // 页面隐藏时，需要将滑块弹回
      this.handleCloseSwipeCell()
    }
  },

  computed: {
    // 全选状态
    allChecked(data) {
      // computed 函数中不能访问 this,要通过形参访问
      return data.cartList.every((item) => item.isChecked === 1)
    },
    // 计算总价
    totalPrice(data) {
      // 先过滤出选中项，再合计
      const selectedCartList = data.cartList.filter((item) => item.isChecked === 1)
      return selectedCartList.reduce((pre, cur) => pre + cur.count * cur.price, 0)
    }
  }
})
